import React, { useState, useEffect } from "react";
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Modal,
  Form,
  Select,
  message,
  Tag,
  Tooltip,
  Progress,
  Rate,
  Upload,
  Typography,
  Row,
  Col,
  Statistic,
  Divider,
  List,
  Avatar,
  Tabs,
  Checkbox,
  Alert,
  Steps,
  Badge,
  Popconfirm,
  Switch,
  Collapse,
  Descriptions,
  Timeline,
} from "antd";
import {
  CheckOutlined,
  CloseOutlined,
  EyeOutlined,
  DownloadOutlined,
  UploadOutlined,
  FileTextOutlined,
  ClockCircleOutlined,
  UserOutlined,
  StarOutlined,
  MessageOutlined,
  RobotOutlined,
  TeamOutlined,
  AuditOutlined,
  RollbackOutlined,
  SendOutlined,
  LoadingOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  SyncOutlined,
  QuestionCircleOutlined,
  FilePdfOutlined,
  EditOutlined,
  CheckSquareOutlined,
  CloseSquareOutlined,
  InfoCircleOutlined,
} from "@ant-design/icons";
import type { UploadFile } from "antd/es/upload/interface";
import { useUser } from "../../../contexts/UserContext";

const { Search } = Input;
const { TextArea } = Input;
const { Title, Text, Paragraph } = Typography;
const { TabPane } = Tabs;
const { Panel } = Collapse;

// 题目作答详情接口
interface QuestionAnswer {
  id: string;
  questionNumber: number;
  questionType: "choice" | "fill" | "essay" | "programming" | "analysis";
  questionContent: string;
  studentAnswer: string;
  correctAnswer: string;
  score: number;
  maxScore: number;
  aiScore: number;
  aiFeedback: string;
  aiReasoning: string;
  teacherScore?: number;
  teacherFeedback?: string;
  isCorrect: boolean;
  options?: string[]; // 选择题选项
}

// 考试提交详情接口
interface ExamSubmission {
  id: string;
  studentId: string;
  studentName: string;
  examId: string;
  examName: string;
  className: string;
  submitTime: string;
  status: "pending" | "ai_graded" | "teacher_reviewed" | "published" | "rejected" | "late";
  score?: number;
  totalScore: number;
  files: UploadFile[];
  comments?: string;
  gradedBy?: string;
  gradedTime?: string;
  
  // AI批阅信息
  aiScore?: number;
  aiComments?: string;
  aiObjectiveScore?: number;
  aiSubjectiveScore?: number;
  aiGradingDetails?: string;
  aiGradingTime?: string;
  aiConfidence?: number; // AI置信度
  
  // 教师审核信息
  teacherScore?: number;
  teacherComments?: string;
  reviewStatus?: "pending" | "approved" | "rejected";
  reviewComments?: string;
  reviewTime?: string;
  
  // 详细作答信息
  questionAnswers?: QuestionAnswer[];
  
  resubmissionCount?: number;
}

interface ExamGradingModalProps {
  visible: boolean;
  submission: ExamSubmission | null;
  onOk: (reviewStatus: string, teacherScore?: number, reviewComments?: string) => void;
  onCancel: () => void;
  loading: boolean;
}

const ExamGradingModal: React.FC<ExamGradingModalProps> = ({
  visible,
  submission,
  onOk,
  onCancel,
  loading,
}) => {
  const [form] = Form.useForm();
  const [reviewStatus, setReviewStatus] = useState<string>("approved");
  const [teacherScore, setTeacherScore] = useState<number | undefined>();
  const [reviewComments, setReviewComments] = useState<string>("");

  useEffect(() => {
    if (submission) {
      setReviewStatus(submission.reviewStatus || "approved");
      setTeacherScore(submission.teacherScore || submission.aiScore);
      setReviewComments(submission.reviewComments || "");
      form.setFieldsValue({
        reviewStatus: submission.reviewStatus || "approved",
        teacherScore: submission.teacherScore || submission.aiScore,
        reviewComments: submission.reviewComments || "",
      });
    }
  }, [submission, form]);

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      onOk(values.reviewStatus, values.teacherScore, values.reviewComments);
    } catch (error) {
      message.error("请填写完整信息");
    }
  };

  const getStatusStep = (submission: ExamSubmission) => {
    if (submission.status === "pending") return 0;
    if (submission.status === "ai_graded") return 1;
    if (submission.status === "teacher_reviewed") return 2;
    if (submission.status === "published") return 3;
    return 0;
  };

  const getQuestionTypeName = (type: string) => {
    const typeMap = {
      choice: "选择题",
      fill: "填空题", 
      essay: "简答题",
      programming: "编程题",
      analysis: "分析题"
    };
    return typeMap[type as keyof typeof typeMap] || type;
  };

  const getQuestionTypeColor = (type: string) => {
    const colorMap = {
      choice: "blue",
      fill: "green",
      essay: "orange", 
      programming: "purple",
      analysis: "cyan"
    };
    return colorMap[type as keyof typeof colorMap] || "default";
  };

  return (
    <Modal
      title={`考试批阅审核 - ${submission?.studentName} (${submission?.examName})`}
      open={visible}
      onOk={handleOk}
      onCancel={onCancel}
      width={1200}
      confirmLoading={loading}
      destroyOnClose
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button 
          key="submit" 
          type="primary" 
          onClick={handleOk}
          loading={loading}
          icon={<CheckOutlined />}
        >
          提交审核
        </Button>
      ]}
    >
      {/* 基本信息 */}
      <div style={{ marginBottom: 16 }}>
        <Row gutter={16}>
          <Col span={6}>
            <Statistic
              title="学生姓名"
              value={submission?.studentName}
              prefix={<UserOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="考试名称"
              value={submission?.examName}
              prefix={<FileTextOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="班级"
              value={submission?.className}
              prefix={<TeamOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="提交时间"
              value={submission?.submitTime}
              prefix={<ClockCircleOutlined />}
            />
          </Col>
        </Row>
      </div>

      <Divider />

      {/* 处理流程状态 */}
      <div style={{ marginBottom: 16 }}>
        <Title level={5}>处理流程</Title>
        <Steps current={submission ? getStatusStep(submission) : 0} size="small">
          <Steps.Step title="待批阅" icon={<ClockCircleOutlined />} />
          <Steps.Step title="AI批阅" icon={<RobotOutlined />} />
          <Steps.Step title="教师审核" icon={<AuditOutlined />} />
          <Steps.Step title="发布成绩" icon={<SendOutlined />} />
        </Steps>
      </div>

      <Divider />

      {/* AI批阅结果概览 */}
      {submission?.aiScore !== undefined && (
        <>
          <div style={{ marginBottom: 16 }}>
            <Title level={5}>
              <RobotOutlined style={{ color: "#1890ff" }} /> AI批阅结果概览
            </Title>
            <Row gutter={16} style={{ marginBottom: 8 }}>
              <Col span={6}>
                <Alert
                  message={`总分: ${submission.aiScore}/${submission.totalScore}`}
                  description="AI综合评分"
                  type="info"
                  showIcon
                />
              </Col>
              <Col span={6}>
                <Alert
                  message={`客观题: ${submission.aiObjectiveScore || 0}/100`}
                  description="标准答案批阅"
                  type="success"
                  showIcon
                />
              </Col>
              <Col span={6}>
                <Alert
                  message={`主观题: ${submission.aiSubjectiveScore || 0}/100`}
                  description="AI智能批阅"
                  type="warning"
                  showIcon
                />
              </Col>
              <Col span={6}>
                <Alert
                  message={`置信度: ${submission.aiConfidence || 85}%`}
                  description="AI批阅置信度"
                  type="info"
                  showIcon
                />
              </Col>
            </Row>
            
            <Alert
              message="AI综合评语"
              description={submission.aiComments}
              type="info"
              showIcon
              style={{ marginBottom: 8 }}
            />
            
            <Alert
              message="批阅时间"
              description={submission.aiGradingTime || "2024-01-18 15:30:00"}
              type="info"
              showIcon
              style={{ marginBottom: 8 }}
            />
          </div>
          <Divider />
        </>
      )}

      {/* 详细题目批阅 */}
      {submission?.questionAnswers && submission.questionAnswers.length > 0 && (
        <>
          <div style={{ marginBottom: 16 }}>
            <Title level={5}>
              <FileTextOutlined /> 详细题目批阅
            </Title>
            <Collapse defaultActiveKey={['0']} ghost>
              {submission.questionAnswers.map((answer, index) => (
                <Panel 
                  header={
                    <Space>
                      <Tag color={getQuestionTypeColor(answer.questionType)}>
                        {getQuestionTypeName(answer.questionType)}
                      </Tag>
                      <Text strong>第{answer.questionNumber}题</Text>
                      <Text>AI评分: {answer.aiScore}/{answer.maxScore}</Text>
                      {answer.isCorrect && <CheckCircleOutlined style={{ color: '#52c41a' }} />}
                      {!answer.isCorrect && <CloseOutlined style={{ color: '#ff4d4f' }} />}
                    </Space>
                  }
                  key={index}
                >
                  <div style={{ padding: '16px 0' }}>
                    {/* 题目内容 */}
                    <div style={{ marginBottom: 16 }}>
                      <Text strong>题目内容：</Text>
                      <div style={{ 
                        background: '#f5f5f5', 
                        padding: '12px', 
                        borderRadius: '6px',
                        marginTop: '8px'
                      }}>
                        {answer.questionContent}
                      </div>
                    </div>

                    {/* 学生答案 */}
                    <div style={{ marginBottom: 16 }}>
                      <Text strong>学生答案：</Text>
                      <div style={{ 
                        background: '#fff7e6', 
                        padding: '12px', 
                        borderRadius: '6px',
                        marginTop: '8px',
                        border: '1px solid #ffd591'
                      }}>
                        {answer.questionType === 'choice' && answer.options ? (
                          <div>
                            <Text>选择: {answer.studentAnswer}</Text>
                            <br />
                            <Text type="secondary">选项: {answer.options.join(' | ')}</Text>
                          </div>
                        ) : (
                          answer.studentAnswer
                        )}
                      </div>
                    </div>

                    {/* 正确答案 */}
                    <div style={{ marginBottom: 16 }}>
                      <Text strong>正确答案：</Text>
                      <div style={{ 
                        background: '#f6ffed', 
                        padding: '12px', 
                        borderRadius: '6px',
                        marginTop: '8px',
                        border: '1px solid #b7eb8f'
                      }}>
                        {answer.correctAnswer}
                      </div>
                    </div>

                    {/* AI批阅反馈 */}
                    <div style={{ marginBottom: 16 }}>
                      <Text strong>
                        <RobotOutlined style={{ color: '#1890ff', marginRight: '4px' }} />
                        AI批阅反馈：
                      </Text>
                      <div style={{ 
                        background: '#e6f7ff', 
                        padding: '12px', 
                        borderRadius: '6px',
                        marginTop: '8px',
                        border: '1px solid #91d5ff'
                      }}>
                        <div style={{ marginBottom: '8px' }}>
                          <Text strong>评分：{answer.aiScore}/{answer.maxScore}</Text>
                        </div>
                        <div style={{ marginBottom: '8px' }}>
                          <Text strong>反馈：</Text>
                          <Text>{answer.aiFeedback}</Text>
                        </div>
                        <div>
                          <Text strong>批阅理由：</Text>
                          <Text>{answer.aiReasoning}</Text>
                        </div>
                      </div>
                    </div>

                    {/* 教师评分（可选） */}
                    <div style={{ marginBottom: 16 }}>
                      <Text strong>
                        <EditOutlined style={{ color: '#faad14', marginRight: '4px' }} />
                        教师评分（可选）：
                      </Text>
                      <div style={{ marginTop: '8px' }}>
                        <Input
                          type="number"
                          placeholder={`0-${answer.maxScore}`}
                          addonAfter={`/ ${answer.maxScore}`}
                          style={{ width: '200px' }}
                          value={answer.teacherScore}
                          onChange={(e) => {
                            const newAnswers = [...submission.questionAnswers!];
                            newAnswers[index].teacherScore = Number(e.target.value);
                            // 这里需要更新submission状态
                          }}
                        />
                        <TextArea
                          placeholder="教师评语（可选）"
                          rows={2}
                          style={{ marginTop: '8px' }}
                          value={answer.teacherFeedback}
                          onChange={(e) => {
                            const newAnswers = [...submission.questionAnswers!];
                            newAnswers[index].teacherFeedback = e.target.value;
                            // 这里需要更新submission状态
                          }}
                        />
                      </div>
                    </div>
                  </div>
                </Panel>
              ))}
            </Collapse>
          </div>
          <Divider />
        </>
      )}

      {/* 学生提交的文件 */}
      <div style={{ marginBottom: 16 }}>
        <Title level={5}>学生提交的文件</Title>
        <List
          itemLayout="horizontal"
          dataSource={submission?.files || []}
          renderItem={(file) => (
            <List.Item
              actions={[
                <Button
                  key="download"
                  type="link"
                  icon={<DownloadOutlined />}
                  onClick={() => window.open(file.url)}
                >
                  下载
                </Button>,
                <Button
                  key="preview"
                  type="link"
                  icon={<EyeOutlined />}
                  onClick={() => window.open(file.url)}
                >
                  预览
                </Button>,
              ]}
            >
              <List.Item.Meta
                avatar={<FilePdfOutlined style={{ fontSize: 24, color: '#ff4d4f' }} />}
                title={file.name}
                description={`大小: ${(file.size || 0) / 1024}KB`}
              />
            </List.Item>
          )}
        />
      </div>

      <Divider />

      {/* 教师审核表单 */}
      <div style={{ marginBottom: 16 }}>
        <Title level={5}>
          <AuditOutlined style={{ color: '#faad14' }} /> 教师审核
        </Title>
        <Alert
          message="审核说明"
          description="请审核AI批阅结果，可以选择通过或修改评分。修改评分后，系统会自动生成相应的评语。"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />
        
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="reviewStatus"
                label="审核结果"
                rules={[{ required: true, message: "请选择审核结果" }]}
              >
                <Select
                  value={reviewStatus}
                  onChange={setReviewStatus}
                  placeholder="请选择审核结果"
                >
                  <Select.Option value="approved">
                    <CheckCircleOutlined style={{ color: "#52c41a" }} /> 通过AI批阅
                  </Select.Option>
                  <Select.Option value="rejected">
                    <ExclamationCircleOutlined style={{ color: "#ff4d4f" }} /> 需要修改
                  </Select.Option>
                </Select>
              </Form.Item>
            </Col>
            
            <Col span={8}>
              <Form.Item
                name="teacherScore"
                label="最终评分"
                rules={[
                  { required: reviewStatus === "rejected", message: "修改时需要填写评分" },
                  { type: "number", min: 0, max: submission?.totalScore || 100, message: "分数超出范围" },
                ]}
              >
                <Input
                  type="number"
                  placeholder={`0-${submission?.totalScore || 100}`}
                  addonAfter={`/ ${submission?.totalScore || 100}`}
                  value={teacherScore}
                  onChange={(e) => setTeacherScore(Number(e.target.value))}
                  disabled={reviewStatus === "approved"}
                />
              </Form.Item>
            </Col>
            
            <Col span={8}>
              <Form.Item
                name="reviewComments"
                label="审核评语"
                rules={[{ required: true, message: "请输入审核评语" }]}
              >
                <TextArea
                  rows={3}
                  placeholder={reviewStatus === "approved" ? "审核通过，AI批阅结果合理。" : "请说明修改原因..."}
                  value={reviewComments}
                  onChange={(e) => setReviewComments(e.target.value)}
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </div>
    </Modal>
  );
};

const ExamGrading: React.FC = () => {
  const { user } = useUser();
  const [loading, setLoading] = useState(false);
  const [submissions, setSubmissions] = useState<ExamSubmission[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [currentSubmission, setCurrentSubmission] = useState<ExamSubmission | null>(null);
  const [searchText, setSearchText] = useState("");
  const [selectedClass, setSelectedClass] = useState<string>("all");
  const [selectedStatus, setSelectedStatus] = useState<string>("all");
  const [selectedRows, setSelectedRows] = useState<string[]>([]);
  const [aiGradingLoading, setAiGradingLoading] = useState(false);
  const [publishLoading, setPublishLoading] = useState(false);
  const [activeTab, setActiveTab] = useState<string>("all");

  // 生成模拟数据
  const generateMockSubmissions = (): ExamSubmission[] => {
    const classNames = ["计算机科学1班", "计算机科学2班", "软件工程1班", "软件工程2班", "人工智能1班"];
    const examNames = ["操作系统期中考试", "数据结构期末考试", "计算机网络期中考试", "数据库原理期末考试", "软件工程期中考试"];
    const studentNames = [
      "李明轩", "王雨涵", "张浩然", "刘雅琪", "陈思远", "杨梦瑶", "赵天宇", "孙诗涵", "周博文", "吴欣怡",
      "徐子轩", "朱雨桐", "胡志强", "郭雅婷", "何俊杰", "马晓雯", "韩志豪", "郑雅文", "冯浩然", "曹梦琪",
      "彭志强", "董雅涵", "袁博文", "潘雨桐", "田志豪", "姜雅文", "魏浩然", "蒋梦琪", "韦志强", "傅雅涵",
      "沈博文", "卢雨桐", "姚志豪", "钱雅文", "汪浩然", "田梦琪", "任志强", "武雅涵", "戴博文", "贾雨桐",
      "夏志豪", "钟雅文", "邱浩然", "骆梦琪", "高志强", "蔡雅涵", "樊博文", "胡雨桐", "凌志豪", "霍雅文"
    ];

    // 生成题目作答详情
    const generateQuestionAnswers = (examName: string): QuestionAnswer[] => {
      const questions: QuestionAnswer[] = [];
      
      // 选择题
      questions.push({
        id: "q1",
        questionNumber: 1,
        questionType: "choice" as const,
        questionContent: "在操作系统中，进程的基本特征不包括以下哪一项？",
        studentAnswer: "B",
        correctAnswer: "A",
        score: 0,
        maxScore: 4,
        aiScore: 0,
        aiFeedback: "答案错误。进程的基本特征包括动态性、并发性、独立性、异步性和结构性。",
        aiReasoning: "学生选择了B选项，但正确答案是A。进程的基本特征中，动态性是指进程是程序的执行过程，具有生命周期。",
        isCorrect: false,
        options: ["动态性", "静态性", "并发性", "独立性"]
      });

      questions.push({
        id: "q2", 
        questionNumber: 2,
        questionType: "choice" as const,
        questionContent: "以下哪种调度算法可能导致饥饿现象？",
        studentAnswer: "A",
        correctAnswer: "A", 
        score: 4,
        maxScore: 4,
        aiScore: 4,
        aiFeedback: "答案正确。短作业优先调度算法可能导致长作业饥饿。",
        aiReasoning: "学生正确选择了A选项。短作业优先调度算法总是优先执行短作业，可能导致长作业长时间得不到执行。",
        isCorrect: true,
        options: ["短作业优先", "先来先服务", "时间片轮转", "优先级调度"]
      });

      // 填空题
      questions.push({
        id: "q3",
        questionNumber: 3,
        questionType: "fill" as const,
        questionContent: "进程的三种基本状态是____、____和____。",
        studentAnswer: "就绪状态、运行状态、阻塞状态",
        correctAnswer: "就绪状态、运行状态、阻塞状态",
        score: 3,
        maxScore: 3,
        aiScore: 3,
        aiFeedback: "答案完全正确。",
        aiReasoning: "学生准确回答了进程的三种基本状态，表述清晰准确。",
        isCorrect: true
      });

      // 简答题
      questions.push({
        id: "q4",
        questionNumber: 4,
        questionType: "essay" as const,
        questionContent: "请简述死锁产生的四个必要条件。",
        studentAnswer: "死锁产生的四个必要条件是：1. 互斥条件：资源不能被多个进程同时使用；2. 请求与保持条件：进程在等待其他资源时，不释放已占有的资源；3. 不剥夺条件：不能强行剥夺进程已占有的资源；4. 循环等待条件：存在一个进程等待链，形成循环等待。",
        correctAnswer: "死锁产生的四个必要条件是：1. 互斥条件；2. 请求与保持条件；3. 不剥夺条件；4. 循环等待条件。",
        score: 7,
        maxScore: 8,
        aiScore: 7,
        aiFeedback: "答案基本正确，但可以更简洁。",
        aiReasoning: "学生正确列出了死锁的四个必要条件，内容完整，但表述可以更简洁。扣1分是因为答案过于冗长。",
        isCorrect: false
      });

      // 编程题
      questions.push({
        id: "q5",
        questionNumber: 5,
        questionType: "programming" as const,
        questionContent: "编写一个函数，实现两个进程之间的生产者-消费者问题。",
        studentAnswer: "void producer() {\n  while(true) {\n    item = produce_item();\n    if(buffer_is_full()) {\n      wait(empty);\n    }\n    insert_item(item);\n    signal(full);\n  }\n}",
        correctAnswer: "完整的生产者-消费者实现需要包含同步机制和缓冲区管理。",
        score: 12,
        maxScore: 15,
        aiScore: 12,
        aiFeedback: "代码逻辑基本正确，但缺少完整的实现。",
        aiReasoning: "学生理解了生产者-消费者的基本概念，使用了信号量机制，但代码不完整，缺少消费者函数和完整的同步处理。",
        isCorrect: false
      });

      return questions;
    };

    return Array.from({ length: 50 }, (_, index) => {
      const statuses: ("pending" | "ai_graded" | "teacher_reviewed" | "published" | "rejected" | "late")[] = 
        ["pending", "ai_graded", "teacher_reviewed", "published", "rejected", "late"];
      const status = statuses[index % statuses.length];
      
      const hasAIGrading = status !== "pending";
      const hasTeacherReview = ["teacher_reviewed", "published"].includes(status);
      const examName = examNames[Math.floor(index / 10)];
      
      // 生成AI评分
      const aiScore = hasAIGrading ? Math.floor(Math.random() * 40) + 60 : undefined;
      const aiObjectiveScore = hasAIGrading ? Math.floor(Math.random() * 20) + 80 : undefined;
      const aiSubjectiveScore = hasAIGrading ? Math.floor(Math.random() * 30) + 70 : undefined;
      
      // 生成题目作答
      const questionAnswers = hasAIGrading ? generateQuestionAnswers(examName) : undefined;
      
      return {
        id: `exam_${index + 1}`,
        studentId: `s${index + 1}`,
        studentName: studentNames[index % studentNames.length],
        examId: `exam_${Math.floor(index / 10) + 1}`,
        examName,
        className: classNames[index % classNames.length],
        submitTime: `2024-01-${String(20 - Math.floor(index / 3)).padStart(2, '0')} ${String(14 + index % 6).padStart(2, '0')}:${String(20 + index % 40).padStart(2, '0')}:00`,
        status,
        score: hasTeacherReview ? Math.floor(Math.random() * 40) + 60 : undefined,
        totalScore: 100,
        files: [
          {
            uid: `file_${index + 1}`,
            name: `考试答案_${studentNames[index % studentNames.length]}.pdf`,
            status: 'done',
            url: '#',
            size: 1024 * 1024,
          }
        ],
        comments: hasTeacherReview ? "学生表现良好，答案完整，思路清晰。" : undefined,
        gradedBy: hasTeacherReview ? user?.name : undefined,
        gradedTime: hasTeacherReview ? `2024-01-${String(21 - Math.floor(index / 3)).padStart(2, '0')} ${String(10 + index % 10).padStart(2, '0')}:${String(30 + index % 30).padStart(2, '0')}:00` : undefined,
        
        // AI批阅信息
        aiScore,
        aiComments: hasAIGrading ? [
          "AI自动评分完成，客观题表现优秀，主观题思路清晰但表述可以更详细。建议在论述题中增加更多实例支撑。",
          "整体表现良好，基础知识掌握扎实，但在复杂问题分析上还有提升空间。",
          "答题认真，逻辑清晰，但在某些细节处理上存在不足。建议加强实践练习。",
          "理解基本概念，但在应用层面还需要加强。建议多做相关练习。",
          "基础知识掌握较好，但在综合运用方面有待提高。"
        ][index % 5] : undefined,
        aiObjectiveScore,
        aiSubjectiveScore,
        aiGradingDetails: hasAIGrading ? "AI批阅完成，包含客观题自动评分和主观题智能分析。" : undefined,
        aiGradingTime: hasAIGrading ? `2024-01-${String(18 - Math.floor(index / 3)).padStart(2, '0')} ${String(15 + index % 5).padStart(2, '0')}:${String(30 + index % 30).padStart(2, '0')}:00` : undefined,
        aiConfidence: hasAIGrading ? Math.floor(Math.random() * 20) + 80 : undefined,
        
        // 教师审核信息
        teacherScore: hasTeacherReview ? Math.floor(Math.random() * 40) + 60 : undefined,
        teacherComments: hasTeacherReview ? "经过教师审核，评分合理。" : undefined,
        reviewStatus: hasTeacherReview ? (status === "published" ? "approved" : "rejected") : undefined,
        reviewComments: hasTeacherReview ? (status === "published" ? "审核通过，可以发布成绩。" : "需要重新批阅。") : undefined,
        reviewTime: hasTeacherReview ? `2024-01-${String(19 - Math.floor(index / 3)).padStart(2, '0')} ${String(9 + index % 10).padStart(2, '0')}:${String(30 + index % 30).padStart(2, '0')}:00` : undefined,
        
        // 详细作答信息
        questionAnswers,
        
        resubmissionCount: status === "rejected" ? 1 : 0,
      };
    });
  };

  const fetchSubmissions = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      const mockData = generateMockSubmissions();
      setSubmissions(mockData);
    } catch (error) {
      message.error("获取考试提交数据失败");
    } finally {
      setLoading(false);
    }
  };

  const gradeExam = async (submissionId: string, reviewStatus: string, teacherScore?: number, reviewComments?: string) => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      setSubmissions(prev => prev.map(submission => {
        if (submission.id === submissionId) {
          return {
            ...submission,
            reviewStatus: reviewStatus as "approved" | "rejected",
            reviewComments: reviewComments || "",
            teacherScore: teacherScore,
            status: reviewStatus === "approved" ? "teacher_reviewed" : "rejected",
            gradedBy: user?.name,
            gradedTime: new Date().toLocaleString(),
          };
        }
        return submission;
      }));
      
      message.success("批阅完成");
      setModalVisible(false);
    } catch (error) {
      message.error("批阅失败");
    } finally {
      setLoading(false);
    }
  };

  const showGradingModal = (submission: ExamSubmission) => {
    setCurrentSubmission(submission);
    setModalVisible(true);
  };

  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  const handleAIBatchGrading = async () => {
    if (selectedRows.length === 0) {
      message.warning("请选择要批量AI批阅的考试");
      return;
    }

    setAiGradingLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      setSubmissions(prev => prev.map(submission => {
        if (selectedRows.includes(submission.id) && submission.status === "pending") {
          // 模拟不同的AI批阅结果
          const gradingResults = [
            {
              objectiveScore: 85,
              subjectiveScore: 78,
              totalScore: 82,
              comments: "客观题表现优秀，主观题思路清晰但表述可以更详细。建议在论述题中增加更多实例支撑。",
              details: "选择题正确率85%，填空题准确率90%，主观题逻辑清晰，但缺乏深度分析。"
            },
            {
              objectiveScore: 92,
              subjectiveScore: 88,
              totalScore: 90,
              comments: "整体表现优秀，客观题准确率高，主观题分析深入，论述充分。",
              details: "选择题正确率92%，填空题准确率95%，主观题分析透彻，举例恰当。"
            },
            {
              objectiveScore: 76,
              subjectiveScore: 82,
              totalScore: 79,
              comments: "客观题有待提高，主观题表现良好。建议加强基础知识掌握。",
              details: "选择题正确率76%，填空题准确率80%，主观题思路清晰，但基础知识有欠缺。"
            },
            {
              objectiveScore: 88,
              subjectiveScore: 75,
              totalScore: 82,
              comments: "客观题表现良好，主观题需要改进。建议加强论述能力和逻辑思维。",
              details: "选择题正确率88%，填空题准确率90%，主观题逻辑性较强，但论述不够深入。"
            },
            {
              objectiveScore: 95,
              subjectiveScore: 85,
              totalScore: 90,
              comments: "客观题表现卓越，主观题分析到位。整体质量很高。",
              details: "选择题正确率95%，填空题准确率98%，主观题分析全面，论述有力。"
            }
          ];
          
          const result = gradingResults[Math.floor(Math.random() * gradingResults.length)];
          
          return {
            ...submission,
            status: "ai_graded",
            aiScore: result.totalScore,
            aiObjectiveScore: result.objectiveScore,
            aiSubjectiveScore: result.subjectiveScore,
            aiComments: result.comments,
            aiGradingDetails: result.details,
            gradedBy: "AI助手",
            gradedTime: new Date().toLocaleString(),
          };
        }
        return submission;
      }));
      
      message.success(`成功完成${selectedRows.length}个考试的AI批阅`);
      setSelectedRows([]);
    } catch (error) {
      message.error("AI批量批阅失败");
    } finally {
      setAiGradingLoading(false);
    }
  };

  const handlePublishGrades = async () => {
    const reviewedSubmissions = submissions.filter(s => s.status === "teacher_reviewed");
    if (reviewedSubmissions.length === 0) {
      message.warning("没有可发布的成绩");
      return;
    }

    setPublishLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      setSubmissions(prev => prev.map(submission => {
        if (submission.status === "teacher_reviewed") {
          return {
            ...submission,
            status: "published",
            score: submission.teacherScore,
            comments: submission.teacherComments,
          };
        }
        return submission;
      }));
      
      message.success(`成功发布${reviewedSubmissions.length}个成绩`);
    } catch (error) {
      message.error("发布成绩失败");
    } finally {
      setPublishLoading(false);
    }
  };

  const handleRejectAndRegrade = async (submissionId: string) => {
    setSubmissions(prev => prev.map(submission => {
      if (submission.id === submissionId) {
        return {
          ...submission,
          status: "pending",
          aiScore: undefined,
          aiComments: undefined,
          aiObjectiveScore: undefined,
          aiSubjectiveScore: undefined,
          aiGradingDetails: undefined,
          teacherScore: undefined,
          teacherComments: undefined,
          reviewStatus: undefined,
          reviewComments: undefined,
          gradedBy: undefined,
          gradedTime: undefined,
          resubmissionCount: (submission.resubmissionCount || 0) + 1,
        };
      }
      return submission;
    }));
    message.success("已打回重批");
  };

  useEffect(() => {
    fetchSubmissions();
  }, []);

  // 统计数据
  const stats = {
    total: submissions.length,
    pending: submissions.filter(s => s.status === "pending").length,
    aiGraded: submissions.filter(s => s.status === "ai_graded").length,
    teacherReviewed: submissions.filter(s => s.status === "teacher_reviewed").length,
    published: submissions.filter(s => s.status === "published").length,
    rejected: submissions.filter(s => s.status === "rejected").length,
  };

  // 班级选项
  const classOptions = Array.from(new Set(submissions.map(s => s.className))).map(className => ({
    label: className,
    value: className,
  }));

  // 状态选项
  const statusOptions = [
    { label: "全部", value: "all" },
    { label: "待批阅", value: "pending" },
    { label: "AI已批阅", value: "ai_graded" },
    { label: "教师已审核", value: "teacher_reviewed" },
    { label: "已发布", value: "published" },
    { label: "已打回", value: "rejected" },
  ];

  // 过滤后的数据
  const filteredSubmissions = submissions.filter(submission => {
    const matchSearch = !searchText || 
      submission.studentName.includes(searchText) ||
      submission.examName.includes(searchText) ||
      submission.className.includes(searchText);
    
    const matchClass = selectedClass === "all" || submission.className === selectedClass;
    const matchStatus = selectedStatus === "all" || submission.status === selectedStatus;
    
    return matchSearch && matchClass && matchStatus;
  });

  const columns = [
    {
      title: "学生姓名",
      dataIndex: "studentName",
      key: "studentName",
      width: 100,
    },
    {
      title: "考试名称",
      dataIndex: "examName",
      key: "examName",
      width: 150,
    },
    {
      title: "班级",
      dataIndex: "className",
      key: "className",
      width: 120,
    },
    {
      title: "提交时间",
      dataIndex: "submitTime",
      key: "submitTime",
      width: 150,
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      width: 120,
      render: (status: string) => {
        const statusConfig = {
          pending: { color: "orange", text: "待批阅", icon: <ClockCircleOutlined /> },
          ai_graded: { color: "blue", text: "AI已批阅", icon: <RobotOutlined /> },
          teacher_reviewed: { color: "green", text: "教师已审核", icon: <AuditOutlined /> },
          published: { color: "green", text: "已发布", icon: <CheckCircleOutlined /> },
          rejected: { color: "red", text: "已打回", icon: <RollbackOutlined /> },
          late: { color: "red", text: "逾期提交", icon: <ExclamationCircleOutlined /> },
        };
        const config = statusConfig[status as keyof typeof statusConfig] || { color: "default", text: status, icon: <QuestionCircleOutlined /> };
        return (
          <Tag color={config.color} icon={config.icon}>
            {config.text}
          </Tag>
        );
      },
    },
    {
      title: "AI评分",
      dataIndex: "aiScore",
      key: "aiScore",
      width: 120,
      render: (score: number, record: ExamSubmission) => {
        if (record.aiScore !== undefined) {
          return (
            <Space direction="vertical" size="small">
              <Space>
                <Text strong>{score}</Text>
                <Text type="secondary">/ {record.totalScore}</Text>
              </Space>
              <Space size="small">
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  客观:{record.aiObjectiveScore || 0}
                </Text>
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  主观:{record.aiSubjectiveScore || 0}
                </Text>
              </Space>
            </Space>
          );
        }
        return <Text type="secondary">-</Text>;
      },
    },
    {
      title: "教师评分",
      dataIndex: "teacherScore",
      key: "teacherScore",
      width: 100,
      render: (score: number, record: ExamSubmission) => {
        if (record.teacherScore !== undefined) {
          return (
            <Space>
              <Text strong>{score}</Text>
              <Text type="secondary">/ {record.totalScore}</Text>
            </Space>
          );
        }
        return <Text type="secondary">-</Text>;
      },
    },
    {
      title: "操作",
      key: "action",
      width: 200,
      render: (_: any, record: ExamSubmission) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => showGradingModal(record)}
          >
            查看
          </Button>
          {record.status === "ai_graded" && (
            <Button
              type="link"
              size="small"
              icon={<AuditOutlined />}
              onClick={() => showGradingModal(record)}
            >
              审核
            </Button>
          )}
          {record.status === "teacher_reviewed" && (
            <Popconfirm
              title="确定打回重批吗？"
              onConfirm={() => handleRejectAndRegrade(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="link"
                size="small"
                danger
                icon={<RollbackOutlined />}
              >
                打回重批
              </Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card title="考试批阅管理" style={{ marginBottom: 16 }}>
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Statistic
              title="总提交数"
              value={stats.total}
              prefix={<FileTextOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="待批阅"
              value={stats.pending}
              valueStyle={{ color: "#fa8c16" }}
              prefix={<ClockCircleOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="AI已批阅"
              value={stats.aiGraded}
              valueStyle={{ color: "#1890ff" }}
              prefix={<RobotOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="教师已审核"
              value={stats.teacherReviewed}
              valueStyle={{ color: "#52c41a" }}
              prefix={<AuditOutlined />}
            />
          </Col>
        </Row>

        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={8}>
            <Search
              placeholder="搜索学生姓名、考试名称或班级..."
              onSearch={handleSearch}
              style={{ width: "100%" }}
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="选择班级"
              value={selectedClass}
              onChange={setSelectedClass}
              style={{ width: "100%" }}
              options={[{ label: "全部班级", value: "all" }, ...classOptions]}
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="选择状态"
              value={selectedStatus}
              onChange={setSelectedStatus}
              style={{ width: "100%" }}
              options={statusOptions}
            />
          </Col>
          <Col span={8}>
            <Space>
              <Button
                type="primary"
                icon={<RobotOutlined />}
                loading={aiGradingLoading}
                onClick={handleAIBatchGrading}
                disabled={selectedRows.length === 0}
              >
                AI批量批阅 ({selectedRows.length})
              </Button>
              <Button
                type="primary"
                icon={<SendOutlined />}
                loading={publishLoading}
                onClick={handlePublishGrades}
                disabled={stats.teacherReviewed === 0}
              >
                发布成绩 ({stats.teacherReviewed})
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      <Card>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="全部考试" key="all" />
          <TabPane tab="待批阅" key="pending" />
          <TabPane tab="AI已批阅" key="ai_graded" />
          <TabPane tab="教师已审核" key="teacher_reviewed" />
          <TabPane tab="已发布" key="published" />
        </Tabs>

        <Table
          columns={columns}
          dataSource={filteredSubmissions.filter(s => 
            activeTab === "all" || s.status === activeTab
          )}
          rowKey="id"
          loading={loading}
          pagination={{
            total: filteredSubmissions.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
          rowSelection={{
            selectedRowKeys: selectedRows,
            onChange: (selectedRowKeys) => setSelectedRows(selectedRowKeys as string[]),
            getCheckboxProps: (record) => ({
              disabled: record.status !== "pending",
            }),
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

              <ExamGradingModal
          visible={modalVisible}
          submission={currentSubmission}
          onOk={(reviewStatus, teacherScore, reviewComments) => 
            currentSubmission && gradeExam(currentSubmission.id, reviewStatus, teacherScore, reviewComments)
          }
          onCancel={() => setModalVisible(false)}
          loading={loading}
        />
    </div>
  );
};

export default ExamGrading; 